package game.manager
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	import game.VO.TileTemplateVO;
	
	/**
	 * ...
	 * @author Kirill Pletnev
	 */
	public class TemplateTileManager extends EventDispatcher
	{
		public static const DEFAULT_TILE_ID:int = -1;
		private static const _instance:TemplateTileManager = new TemplateTileManager();
		
		private var _tilesVector:Vector.<TileTemplateVO>;
		private var _tilesDictionary:Dictionary;
		private var _loaded:Boolean;
		private var _lastTileID:int;
		
		public function TemplateTileManager()
		{
			if (_instance == null)
			{
				_loaded = false;
				_tilesVector = new Vector.<TileTemplateVO>();
				_tilesDictionary = new Dictionary();
			}
			else
			{
				throw new Error("TemplateTileManager instance already existing in Singleton");
			}
		}
		
		static public function get instance():TemplateTileManager
		{
			return _instance;
		}
		
		public function addNewTile(tileVO:TileTemplateVO):void
		{
			if (tileVO.id == DEFAULT_TILE_ID)
			{
				tileVO.id = _lastTileID;
				_lastTileID++;
			}
			_tilesVector.push(tileVO);
			_tilesDictionary[tileVO.id] = tileVO;
		}
		
		public function get tiles():Vector.<TileTemplateVO>
		{
			return _tilesVector;
		}
		
		public function getTemplateTileById(id:int):TileTemplateVO
		{
			return _tilesDictionary[id];
		}
		
		public function get loaded():Boolean
		{
			return _loaded;
		}
		
		public function loadAll(fileUrl:String):void
		{
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onLoadedLib);
			loader.addEventListener(IOErrorEvent.IO_ERROR, errorLoadLib);
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.load(new URLRequest(fileUrl));
		}
		
		private function onLoadedLib(e:Event):void
		{
			var loader:URLLoader = e.target as URLLoader;
			var data:ByteArray = ByteArray(loader.data);
			deserialize(data);
			finishLoading();
			
			loader.removeEventListener(Event.COMPLETE, onLoadedLib);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, errorLoadLib);
		}
		
		private function errorLoadLib(e:IOErrorEvent):void
		{
			trace("[ERROR]: Had problem loading the tils lib file.");
			trace(e.toString());
			
			throw new Error("Had problem loading the tils lib file.");
		}
		
		private function finishLoading():void
		{
			_loaded = true;
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		// SERIALIZATION ========================================================================
		public function serialize(data:ByteArray):void
		{
			data.writeInt(_lastTileID);
			data.writeInt(_tilesVector.length);
			
			for each (var tileVO:TileTemplateVO in _tilesVector)
			{
				tileVO.serialize(data);
			}
		}
		
		public function deserialize(data:ByteArray):void
		{
			try
			{
				_lastTileID = data.readInt();
				
				var countTileVO:int = data.readInt();
				var tileVO:TileTemplateVO;
				for (var index:int = 0; index < countTileVO; index++)
				{
					tileVO = TileTemplateVO.deserialize(data);
					addNewTile(tileVO);
				}
			}
			catch (error:Error)
			{
				trace("ERROR: deserialize tile manager");
				trace(error.getStackTrace());
			}
		}
	
	}

}